import { BrowserWindow, ipcMain, IpcMainEvent } from 'electron'
import { isEqual } from 'lodash'

class GlobalState {
  globalState: any

  noticeAllWindows(state: any) {
    //获取到所有的窗口并进行更新
    const windows = BrowserWindow.getAllWindows()
    windows.forEach((window) => {
      window.webContents.send('globalStateUpdated', state)
    })
  }

  uploadGlobalState() {
    ipcMain.on('updateGlobalState', (_: IpcMainEvent, newState: any) => {
      //比较一下是不是不一样
      if (!isEqual(this.globalState, newState)) {
        this.globalState = newState
        //通知所有窗口
        this.noticeAllWindows(this.globalState)
      }
    })
  }
}

export const globalState = new GlobalState()
